import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { NavBar } from 'react-vant'
let timer: NodeJS.Timeout
const Index: React.FC = () => {
  const [result, setResult] = useState('交易查询中...')
  const [searchParams] = useSearchParams()
  const out_trade_no = searchParams.get('out_trade_no');

  const query = async () => {
    const resp = await axios.get('/api/query', { params: { out_trade_no } });
    if (resp.data.data.code === '10000') {
      switch (resp.data.data.tradeStatus) {
        case 'WAIT_BUYER_PAY':
          setResult('交易创建，等待买家付款');
          break;
        case 'TRADE_CLOSED':
          setResult('未付款交易超时关闭，或支付完成后全额退款');
          break;
        case 'TRADE_SUCCESS':
          setResult('交易支付成功');
          break;
        case 'TRADE_FINISHED':
          setResult('交易结束，不可退款');
          break;
      }
      clearInterval(timer)
    }
  }

  useEffect(() => {
    query();
    // 轮询
    timer = setInterval(query, 2000);

    return () => {
      clearInterval(timer)
    }
  }, [])

  return (
    <div>
      <NavBar title="支付结果"></NavBar>
      <div className='result'>
        <h1>{result}</h1>
      </div>
    </div>
  )
}

export default Index
